package com.intel.bluetooth;

import com.mlnx.mptp.model.ecg.ECGChannelType;
import com.mlnx.mptp.mptp.MpPacket;
import com.mlnx.util.ThreadUtil;

import javax.bluetooth.RemoteDevice;
import javax.microedition.io.Connector;
import java.io.IOException;

public class ConnectService {

    private BluetoothRFCommClientConnection clientSession = null;

    private RemoteDevice remoteDevice;

    private String bluetoothAddress;

    private ComBluDeviceThread comBluDeviceThread;

    public ConnectService(String bluetoothAddress) {
        this.bluetoothAddress = bluetoothAddress;
    }

    public void connectDevice() {

        ThreadUtil.execute(new Runnable() {

            @Override
            public void run() {
                final String serverURL = "btspp://"
                        + bluetoothAddress
                        + ":1;authenticate=false;encrypt=false;master=false";

                try {
                    clientSession = (BluetoothRFCommClientConnection) Connector
                            .open(serverURL);
                } catch (IOException e) {
                    e.printStackTrace();
                    System.err.println("连接设备失败");
                    return;
                }

                comBluDeviceThread = new ComBluDeviceThread(
                        remoteDevice, clientSession);
                boolean success = comBluDeviceThread.initData();

                if (success) {
                    comBluDeviceThread.start();
                } else {
                    System.err.println("建立设备数据失败");
                }

            }
        });

    }

    public void start() {
        byte[] encode = new MpPacket().startEcg().encode();
        comBluDeviceThread.send(encode, encode.length);
    }

    public void stop() {
        byte[] encode = new MpPacket().stopEcg().encode();
        comBluDeviceThread.send(encode, encode.length);
    }

    public void config(ECGChannelType ecgChannelType) {

        byte[] encode = new MpPacket().configECGChannelType(ecgChannelType).encode();
        comBluDeviceThread.send(encode, encode.length);
    }

    public static void printHexString(byte[] b) {
        for (int i = 0; i < b.length; i++) {
            String hex = Integer.toHexString(b[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            System.out.print(hex.toUpperCase() + " ");
        }

    }

    public static void main(String[] args) {
//        ConnectService connectService = new ConnectService("000666D0D9B2");
//        connectService.connectDevice();
        byte[] encode = new MpPacket().startEcg().encode();

        printHexString(encode);

        encode = new MpPacket().stopEcg().encode();

        printHexString(encode);
    }
}
